<?php

namespace App\Traits;

use Illuminate\Http\UploadedFile;

trait HasFileActions
{
    public function token()
    {
        $data = $this->getTable() . '_' . $this->id;
        return base64_encode(hash_hmac('sha256', $data, $this->id));
        //return base64_encode(openssl_encrypt(serialize($data), 'DES-ECB', self::SECRET));
    }

    public function checkToken($token = '')
    {
        $token = $token ?: request()->get('token', '');
        $data = $this->getTable() . '_' . $this->id;
        return $token && hash_equals(base64_encode(hash_hmac('sha256', $data, $this->id)), $token);
        //unserialize(openssl_decrypt(base64_decode($token), 'DES-ECB', self::SECRET));
    }

    public function uploadDirectory($directory = null): string
    {
        $directory = $directory ?: config('admin.upload.directory.file');
        return $directory . '/' . date('Ym', strtotime($this->created_at));
    }

    public function storeFile(UploadedFile $file, $column, $path = null, array $data = [])
    {

        $path = admin_store($file, $path);
        admin_storage_unlink($this->$column);
        $this->$column = $path;
        foreach ($data as $col => $val) {
            $this->$col = $val;
        }
        $this->save();
    }

}
